import { _decorator, Component, Node, EventTouch, Vec3 , UITransform, Label, math, Widget, Camera, Prefab, instantiate } from 'cc';
import { EventManager } from '../core/EventManager';
import { Game } from '../core/Game';
import { SendWebSocket } from '../websocket/SendWebSocket';
import { Databus } from '../core/Databus';

const { ccclass, property } = _decorator;
const databus = Databus.Instance();
@ccclass('ChatOperateController')
export class ChatOperateController extends Component {
  @property(Camera)
  private UICamera: Camera = null;

  @property(Prefab)
  EmojiPrefab: Prefab = null;
  public static ShowTimestamp = 120;
  // 方向面板控制参数
  private chatOperationSwitch: Node = null;
  private chatOperateController: Node = null;
  private chatTypeSwitch: Node = null;
  private oppoChatContent: Node = null;
  private oppoChatContentLabel: Label = null;
  private selfChatContent: Node = null;
  private selfChatContentLabel: Label = null;

  private clickPoint: math.Vec2 = new math.Vec2(0, 0);
  private chatType = 0; // 0 表情 1 文字
  private textList = [];
  private emojiList = [];
  private emojiPosList: Vec3[] = [];
  private otimestamp = 0;
  private stimestamp = 0;
  onLoad() {
    this.chatType = 0;
    this.chatOperationSwitch = this.node.getChildByName('ChatSwitch');
    this.chatOperateController = this.node.getChildByName('ChatOperateController');
    this.chatTypeSwitch = this.chatOperateController.getChildByName('ChatSwitchButton');
    this.chatOperateController.on(Node.EventType.TOUCH_END, this.chooseChatText, this);
    this.chatOperationSwitch.on(Node.EventType.TOUCH_END, this.switchOperation, this);
    this.chatTypeSwitch.on(Node.EventType.TOUCH_END, this.switchChatType, this)
    this.chatOperateController.active = false;

    // 内容展示控制
    this.oppoChatContent = this.node.getChildByName('ChatContentController').getChildByName('OppoChatContent');
    this.oppoChatContentLabel = this.node.getChildByName('ChatContentController').getChildByName('OppoChatContent').getComponent(Label);
    this.selfChatContent = this.node.getChildByName('ChatContentController').getChildByName('SelfChatContent');
    this.selfChatContentLabel = this.node.getChildByName('ChatContentController').getChildByName('SelfChatContent').getComponent(Label);

    this.textList = [
      '快点吧！等的花儿都谢了！',
      '你的球打的也太好了！',
      '哎呀，失误了，失误了！',
      '果然得靠大力出奇迹呀！',
      '七分技术，三分运气',
      '给个上手的机会呀！'
    ];

    this.emojiList = [
      "🤙", "🤝", "👻", "😎",
      "😡", "🙈", "🌹", "🧨",
      "✨", "🎉", "🎁", "🧧",
      "🏆", "❤", "🖤", "💯",
      "💥", "💫", "🌙", "💢",
      "😷", "🤒", "🙏", "🤺"
    ];

    EventManager.Instance().AddEventListener('OppoNetChatContent', this, this.oppoNetChatContent);
    EventManager.Instance().AddEventListener('SelfNetChatContent', this, this.selfNetChatContent);
    EventManager.Instance().AddEventListener('TouchClickPoint', this, this.touchClickPoint);
    EventManager.Instance().AddEventListener('StartGame', this, this.startGame);

    this.otimestamp = ChatOperateController.ShowTimestamp;
    this.stimestamp = ChatOperateController.ShowTimestamp;
    this.aliginMargin();
    this.loadEmojiList();
  }
  aliginMargin() {
    const widget = this.node.getComponent(Widget);
    widget.right = databus.sceenSize.alignMargin();
    
    // 聊天内容和头像距离对齐
    const selfWidget = this.selfChatContent.getComponent(Widget);
    selfWidget.left = databus.sceenSize.alignMargin() - 10 + 180;
    const oppoWidget = this.oppoChatContent.getComponent(Widget);
    oppoWidget.right = databus.sceenSize.alignMargin() - 10 + 180;
  }
  public startGame() {
    this.hideOperateController();
    this.otimestamp = ChatOperateController.ShowTimestamp;
    this.stimestamp = ChatOperateController.ShowTimestamp;
  }
  update(deltaTime: number) {
    // 1. 展示对手的聊天内容信息
    this.otimestamp += 1;
    if (this.otimestamp >= ChatOperateController.ShowTimestamp) {
      this.oppoChatContent.active = false;
    }

    // 2. 展示自己的聊天内容信息
    this.stimestamp += 1;
    if (this.stimestamp >= ChatOperateController.ShowTimestamp) {
      this.selfChatContent.active = false;
    }

    if (this.chatType === 0) {
      this.chatOperateController.getChildByName('TextList').active = false;
      this.chatOperateController.getChildByName('EmojiList').active = true;
      this.chatOperateController.getChildByName('ChatSwitchButton').getChildByName('ChatTextButton').active = false;
      this.chatOperateController.getChildByName('ChatSwitchButton').getChildByName('ChatEmojiButton').active = true;
    } else {
      this.chatOperateController.getChildByName('TextList').active = true;
      this.chatOperateController.getChildByName('EmojiList').active = false;

      this.chatOperateController.getChildByName('ChatSwitchButton').getChildByName('ChatTextButton').active = true;
      this.chatOperateController.getChildByName('ChatSwitchButton').getChildByName('ChatEmojiButton').active = false;
    }
  }
  public switchChatType() {
    this.chatType = 1 - this.chatType;
  }
  public touchClickPoint(name: string, e: EventTouch) {
    this.chatOperateController.active = false;
  }
  public oppoNetChatContent(name: string, data: any) {
    this.otimestamp = 0;
    this.oppoChatContent.active = true;
    if (data.cType === 0) {
      this.oppoChatContentLabel.fontSize = 60;
    } else {
      this.oppoChatContentLabel.fontSize = 30;
    }
    this.oppoChatContentLabel.string = data.content;
  }

  public selfNetChatContent(name: string, data: any) {
    this.stimestamp = 0;
    this.selfChatContent.active = true;
    if (data.cType === 0) {
      this.selfChatContentLabel.fontSize = 60;
    } else {
      this.selfChatContentLabel.fontSize = 30;
    }
    this.selfChatContentLabel.string = data.content;
    if (Game.Instance().battleCate.isNetBattle()) {
      if (data.cType === 0) {
        setTimeout(() => {
          this.aiAnswerEmojis(data.content);
        }, 3000 + 5000 * Math.random());
      } else {
        setTimeout(() => {
          this.aiAnswerText(data.content);
        }, 3000 + 5000 * Math.random());
      }
    }
  }
  public switchOperation(e: EventTouch) {
    if (this.chatOperateController.active) {
      this.hideOperateController();
      return;
    }
    this.showOperateController();
  }
  public chooseChatText(e: EventTouch) {
    e.getLocation(this.clickPoint);
    const tourchPoint = new Vec3();
    tourchPoint.set(this.clickPoint.x, this.clickPoint.y, 0);
    const out = new Vec3();
    this.UICamera.screenToWorld(tourchPoint, out);
    const uip = this.node.getChildByName('ChatOperateController').getComponent(UITransform);
    const ap = uip.convertToNodeSpaceAR(out);
    // 靠右边，不合适
    if (ap.x >= 105 && ap.x <= 180) { return; }
    var content = '';
    if (this.chatType === 0) {
      const index = this.emojiPositionToIndex(ap);
      console.log(index, ap);
      if (index >= 0 && index < this.emojiList.length) {
        content = this.emojiList[index];
      }
    } else {
      const index = Math.ceil((ap.y + 200) / 67);
      console.log('send chat content ', index, ap.y, this.clickPoint.y);
      if (index > 0 && index <= this.textList.length) {
        content = this.textList[this.textList.length - index];
      }
    }

    if (content !== '') {
      new SendWebSocket().sendChatContent(this.chatType, content);
      if (Game.Instance().battleCate.isFrientBattle() || Game.Instance().battleCate.isNetBattle()) {
        this.selfNetChatContent('SelfNetChatContent', { cType: this.chatType, content: content });
      }
    }
    this.hideOperateController();
  }
  public hideOperateController() {
    this.chatOperateController.active = false;
  }

  public showOperateController() {
    this.chatOperateController.active = true;
  }

  public aiAnswerEmojis(text: string) {
    if (Math.random() > 0.3) { // 30% 回复
      return;
    }
    const emojiAnswerDict: Map<string, Array<string> >  = new Map([
      ["ALL", ["🤙", "🤝", "👻", "😎", "😡", "🙈", "🌹", "🧨", "✨", "🎉", "🎁", "🧧", "🏆", "❤", "🖤", "💯", "💥", "💫", "🌙", "💢", "😷", "🤒", "🙏", "🤺"] ],
      ["*", ["🤝", "👻", "😎", "🌹", "🧨", "✨", "🎉", "🎁", "🧧", "🏆", "❤","💯", "💥", "💫", "🌙", "💢" ] ],
      ["😷", [] ],
      ["🤒", [] ],
      ["🙏", [] ],
      ["🤺", [] ],
    ]);
    const hasAnswer = emojiAnswerDict.has(text);
    if (hasAnswer) {
      const textList = emojiAnswerDict.get(text);
      if (textList.length <= 0) {
        return;
      }
      const index = Math.floor(Math.random() * textList.length);
      const content = textList[index];
      this.oppoNetChatContent("AiAnswer", { cType: 0, content: content });
    } else {
      const textList = emojiAnswerDict.get("*");
      const index = Math.floor(Math.random() * textList.length);
      const content = textList[index];
      this.oppoNetChatContent("AiAnswer", { cType: 0, content: content });
    }
  }
  public aiAnswerText(text: string) {
    if (Math.random() > 0.4) { // 40% 回复
      return;
    }
    const emojiAnswerDict: Map<string, Array<string> >  = new Map([
      ["ALL", ["🤙", "🤝", "👻", "😎", "😡", "🙈", "🌹", "🧨", "✨", "🎉", "🎁", "🧧", "🏆", "❤", "🖤", "💯", "💥", "💫", "🌙", "💢", "😷", "🤒", "🙏", "🤺"] ],
      ["快点吧！等的花儿都谢了！", ["😎", "😡", "🙈", "✨", "🎉", "🖤", "💯", "😷", "🤒", "🙏", "🤺"] ],
      ["你的球打的也太好了！", ["🤝", "👻", "😎", "🧨", "🎉", "🎁", "🏆", "❤", "💯" ]],
      ["哎呀，失误了，失误了！", ["七分技术，三分运气", "👻", "😎", "😡", "🙈", "🌹", "🧨", "✨", "🎉", "🎁", "🧧", "🏆", "❤", "🖤", "💯", "💥", "💫", "🌙", "💢", "🤒", "🙏", "🤺"] ],
      ["果然得靠大力出奇迹呀！", ["🤙", "🤝", "👻", "😎", "😡", "🙈", "💯", "💥", "💫", "🌙", "💢", "🤺"] ],
      ["七分技术，三分运气", ["🤙", "🤝", "👻", "😎", "😡", "🙈", "💯", "💥", "💫", "🌙", "💢", "🤺"] ],
      ["给个上手的机会呀！", ["🤙", "🤝", "👻", "😎", "🧧", "🏆", "💯", "💥", "💫", "🌙", "💢", "🤺"] ],
    ]);
    const hasAnswer = emojiAnswerDict.has(text);
    if (hasAnswer) {
      const textList = emojiAnswerDict.get(text);
      if (textList.length <= 0) {
        return;
      }
      const index = Math.floor(Math.random() * textList.length);
      const content = textList[index];
      this.oppoNetChatContent("AiAnswer", { cType: 0, content: content });
    }
  }
  private loadEmojiList() {
    const emojiNode = this.chatOperateController.getChildByName('EmojiList');
    const pos = new Vec3();
    for (var i=0; i<this.emojiList.length; i++) {
      const row = Math.floor(i/4);
      const col = i % 4;
      const emoji = instantiate(this.EmojiPrefab);
      emoji.active = true;
      emoji.getChildByName('Text').getComponent(Label).string = this.emojiList[i];
      pos.set(-170 + 33 + col * 67, -row * 67 - 33 + 200, 0);
      emoji.setPosition(pos);
      emoji.setParent(emojiNode);
      this.emojiPosList.push(pos.clone());
    }
  }

  private emojiPositionToIndex(pos: Vec3) {
    console.log(pos, this.emojiPosList);
    for (var i=0; i<this.emojiPosList.length; i++) {
      const p = this.emojiPosList[i];
      const dist = (p.x - pos.x) * (p.x - pos.x) + (p.y - pos.y) * (p.y - pos.y);
      if (dist < 900) {
        return i;
      }
    }
    return -1;
  }
}